var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// 中间件
const auth = require('./middleware/auth');
const formatResponse = require('./middleware/response');
const formatPagination = require('./middleware/pagination');

// 路由
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const userInfoRouter = require('./routes/userInfo');
const recordRouter = require('./routes/record');
const supplierRouter = require('./routes/supplier');
const productRouter = require('./routes/product');
const activationRouter = require('./routes/activation');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 注册全局中间件
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 注册自定义中间件
app.use(formatResponse);
app.use(formatPagination);

// 这些路由不需要验证token
app.use('/user', usersRouter);

// 这些路由需要验证token
app.use('/store', auth, indexRouter);

// 用户信息路由
app.use('/userInfo', auth, userInfoRouter);

// 公司路由
app.use('/supplier', auth, supplierRouter);

// 商品路由
app.use('/product', auth, productRouter);

// 记录路由
app.use('/record', auth, recordRouter);

// 激活码路由
app.use('/activation', auth, activationRouter);

// 注册分页中间件
app.use(formatPagination);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
